import { resolve } from 'path'
import { readFileSync } from 'fs'
import MarkdownIt from 'markdown-it'
import Token from 'markdown-it/lib/token'
import { mdCodeBlock } from '../utils/mdCodeBlock'
import { parse, compileScript, compileTemplate } from '@vue/compiler-sfc'

/**
 * @description: 获取文件内容
 * @param {string} path - 文件路径
 * @return {string} - 文件字符
 */
function getFileContent(path: string) {
  try {
    return readFileSync(resolve(__dirname, '../../src', `${path}.vue`), 'utf-8')
  } catch (error) {
    return ''
  }
}

export const examplePlugin = (md: MarkdownIt) => {
  md.use(require('markdown-it-container'), 'example', {
    validate(params: string | undefined) {
      return !!(params || '').trim().match(/^example\s*(.*)$/)
    },

    render(tokens: Token[], idx: number) {
      if (tokens[idx].nesting === 1) {
        const row = tokens[idx]
        const params = row.info.split(/\s/g)
        // 获取描述信息
        const description = params.slice(1).join(' ')

        // 获取首个内容
        const sourceFileToken = tokens[idx + 2]
        let lines: string[] = []
        const sourceFile = sourceFileToken.children?.[0].content ?? ''

        // 读取文件内容
        if (sourceFileToken.type === 'inline') {
          lines = getFileContent(sourceFile).split('\n')
        }

        const content = lines.join('\n')
        return `<m-example 
          source="${encodeURIComponent(md.render(mdCodeBlock(content)))}" 
          path="${sourceFile}" 
          raw-source="${encodeURIComponent(content)}" 
          description="${encodeURIComponent(md.render(description))}">`
      } else {
        return '</m-example>'
      }
    }
  })
}

export const demoPlugin = (md: MarkdownIt) => {
  md.use(require('markdown-it-container'), 'demo', {
    validate(params: string | undefined) {
      return !!(params || '').trim().match(/^demo\s*(.*)$/)
    },

    render(tokens: Token[], idx: number) {
      const { info, nesting } = tokens[idx]
      if (nesting === 1) {
        const component = info.trim().split(/\s+/g)?.[1] || 'div'
        return `<m-demo><${component}></${component}><template #code>`
      } else {
        return '</template></m-demo>'
      }
    }
  })
}

export const mermaidViewerPlugin = (md: MarkdownIt) => {
  md.use(require('markdown-it-container'), 'mermaid-viewer', {
    validate(params: string | undefined) {
      return !!(params || '').trim().match(/^mermaid-viewer\s*(.*)$/)
    },

    render(tokens: Token[], idx: number) {
      const { nesting } = tokens[idx]
      if (nesting === 1) {
        return `<m-mermaid-viewer>`
      } else {
        return '</m-mermaid-viewer>'
      }
    }
  })
}
